﻿using System.Text;

namespace SyncFileCommon.Class
{
    public static class MessageHelper
    {

        /// <summary>
        /// 讲消息类型头和数据合并
        /// </summary>
        /// <param name="cmd">消息类型头</param>
        /// <param name="data">数据</param>
        /// <param name="size">数据长度</param>
        /// <returns></returns>
        public static byte[] CopyMessageHeadTo<T>(T cmd, byte[] data, int size)
            where T : struct
        {
            byte[] buff = new byte[size + sizeof(short)];
            BitConverter.GetBytes(Convert.ToInt16(cmd)).CopyTo(buff, 0);
            Array.Copy(data, 0, buff, sizeof(Int16), size);

            return buff;
        }

        /// <summary>
        /// 构建消息至数据头部
        /// </summary>
        /// <param name="cmd">消息类型头</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public static byte[] CopyMessageHeadTo<T>(T cmd, byte[] data = null)
            where T : struct
        {
            if (data == null)
                data = Array.Empty<byte>();

            return CopyMessageHeadTo(cmd, data, data.Length);
        }

        /// <summary>
        /// 构建消息头至数据头部
        /// </summary>
        /// <param name="cmd">消息头</param>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static byte[] CopyMessageHeadTo<T>(T cmd, string str)
            where T : struct
        {
            byte[] data = Encoding.UTF8.GetBytes(str);

            return CopyMessageHeadTo(cmd, data, data.Length);
        }

        /// <summary>
        /// 获取消息头
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static T GetMessageHead<T>(this byte[] data)
            where T : struct
        {
            if (data == null)
            {
                return default(T);
            }
            return (T)Enum.ToObject(typeof(T), BitConverter.ToInt16(data, 0));
        }


        /// <summary>
        /// 获取字符串消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string GetMessageStringData(this byte[] data)
        {
            if (data == null)
            {
                return string.Empty;
            }

            return System.Text.Encoding.UTF8.GetString(MessageHelper.GetMessageData(data));
        }

        /// <summary>
        /// 获取消息载体
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] GetMessageData(this byte[] data)
        {
            if (data == null)
            {
                return null;
            }

            byte[] _data = new byte[data.Length - sizeof(short)];
            Array.Copy(data, sizeof(short), _data, 0, _data.Length);
            return _data;
        }





    }
}
